package leetcode.栈队列堆;

import java.util.Stack;

/**
 * 逆波兰表达式求值
 */
public class Test150逆波兰表达式求值 {

    public static int evalRPN(String[] tokens) {
        Stack<String> stack = new Stack<>();
        for (int i = 0; i < tokens.length; i++) {
            if (tokens[i].equals("+") || tokens[i].equals("-") ||
                    tokens[i].equals("*")  || tokens[i].equals("/") ) {
                Integer firstPop = Integer.valueOf(stack.pop());
                Integer secondPop = Integer.valueOf(stack.pop());
                Integer result = null;
                if (tokens[i].equals("+")) {
                    result = secondPop + firstPop;
                } else if (tokens[i].equals("-")) {
                    result = secondPop - firstPop;
                } else if (tokens[i].equals("*")) {
                    result = secondPop * firstPop;
                } else {
                    result = secondPop / firstPop;
                }
                stack.push(String.valueOf(result));
            } else {
                stack.push(tokens[i]);
            }
        }

        return Integer.valueOf(stack.pop());
    }

    public static void main(String[] args) {
//       String[] tokens = {"2", "1", "+", "3", "*"};
//       String[] tokens = {"4", "13", "5", "/", "+"};
       String[] tokens = {"10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"};
        System.out.println(evalRPN(tokens));
    }
}
